import React, {Component, ReactNode, Suspense} from 'react';
import {Redirect, Route, Router, Switch} from "react-router-dom";
import {authRouter, IRouter, unAuthRouter} from "../router";
import { createBrowserHistory } from "history";
import AppLayout from "./AppLayout";


class View extends Component {
    // 递归生成路由
    generateRouter = (routerList : IRouter[]) : ReactNode =>{
        return routerList.map(r => {
            if (r.children) { // 如果有子路由
                     return  this.generateRouter(r.children)
            }
            return <Route key={r.title + r.path} path={r.path} exact={r.exact}>
                {r.component}
            </Route>
        })

    }
    render() {
        return (
            <>
                <Suspense fallback={<></>}>
                    <Router history={createBrowserHistory()}>
                        <Switch>
                            {/*如果浏览器跳到/则重定向到/dashboard*/}
                            <Route path={'/'} exact>
                                <Redirect to={'/admin/dashboard'}/>
                            </Route>
                            <Route path={'/admin'}>
                                <AppLayout>
                                    {this.generateRouter(authRouter)}
                                </AppLayout>

                            </Route>
                            <Switch>
                                {unAuthRouter.map(r => (
                                    <Route key={r.title + r.path} path={r.path} exact={r.exact}>
                                        {r.component}
                                    </Route>
                                ))}
                            </Switch>
                        </Switch>
                    </Router>
                </Suspense>
            </>
        );
    }
}

export default View;
